package com.speily.zookeeperdemo;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;

/**
 * @Auther: SPL
 * @Date: 2019-08-12 11:50
 * @Description: -
 */
public class CuratorListenerTest1 {

    public static void main(String[] args) {
        CuratorFramework client = getClient();
        String path = "/p3";
        try {
//            client.create().forPath(path,"new content".getBytes());
            client.getData().usingWatcher(
                            (Watcher) watchedEvent -> System.out.println("1监听器watchedEvent：" + watchedEvent)
                    ).forPath(path);

            // 第一次变更节点数据
            client.setData().forPath(path,"new content".getBytes());
            // 第二次变更节点数据
            client.getData().usingWatcher(
                    (Watcher) watchedEvent -> System.out.println("2监听器watchedEvent：" + watchedEvent)
            ).forPath(path);
            client.setData().forPath(path,"second content".getBytes());


            Thread.sleep(Integer.MAX_VALUE);
        } catch (Exception e) {
            e.printStackTrace();
            client.close();
        } finally {
            client.close();
        }
    }
    private static CuratorFramework getClient(){
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000,3);
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("47.94.165.79:2181")
                .retryPolicy(retryPolicy)
                .sessionTimeoutMs(6000)
                .connectionTimeoutMs(3000)
                .namespace("demo")
                .build();
        client.start();
        return client;
    }


}
